import { css } from '@emotion/css';
import { useEffect, useMemo, useRef, useState } from 'react';
import { ActionImpl, useKBar, VisualState } from 'kbar';
import { FocusScope } from '@react-aria/focus';
import { EmptyState, LoadingBar, Button, Icon, useStyles2 } from '@grafana/ui';
import { t } from '@grafana/i18n';
import { useSearchResults } from 'app/features/commandPalette/actions/dashboardActions';
import { useMatches } from 'app/features/commandPalette/useMatches';
import { CommandPaletteAction } from 'app/features/commandPalette/types';
import { GrafanaTheme2, PageLayoutType } from '@grafana/data';
import { Page } from 'app/core/components/Page/Page';
import { useGrafana } from 'app/core/context/GrafanaContext';
import { ResultItem } from 'app/features/commandPalette/ResultItem';
import { useRegisterRecentDashboardsActions } from 'app/features/commandPalette/actions/useActions';
import { useRegisterRecentScopesActions } from 'app/features/commandPalette/actions/scopeActions';
import { useLocationService } from '@grafana/runtime';
import { backendSrv } from 'app/core/services/backend_srv';

export const DashboardHomePage = () => {
  const styles = useStyles2(getStyles);
  const { chrome } = useGrafana();
  const location = useLocationService();
  const searchRef = useRef<any>(null);

  const { query, search, currentRootActionId, activeIndex, showing, options } = useKBar((state) => ({
    search: state.searchQuery,
    currentRootActionId: state.currentRootActionId,
    actions: state.actions,
    activeIndex: state.activeIndex,
    showing: state.visualState === VisualState.showing,
  }));

  const [inputValue, setInputValue] = useState(search);

    useRegisterRecentDashboardsActions();
    useRegisterRecentScopesActions();

  const { searchResults, isFetchingSearchResults } = useSearchResults({ 
    searchQuery: inputValue,
    show: !currentRootActionId
  });

  const { results: kbarResults, rootActionId } = useMatches();

  useEffect(() => {
    query.setSearch('');
    query.getInput().focus();
    setInputValue('');
    return () => query.setSearch('');
  }, [currentRootActionId, query]);

  const formattedResults = useMemo(() => {
    const results = [...kbarResults];
    const dashboardsSectionTitle = t('command-palette.section.dashboard-search-results', 'Dashboards');
    const foldersSectionTitle = t('command-palette.section.folder-search-results', 'Folders');

    const dashboardItems = (searchResults as CommandPaletteAction[])
      .filter(item => item.id.startsWith('go/dashboard'))
      .map(item => new ActionImpl(item, { store: {} }));

    const folderItems = (searchResults as CommandPaletteAction[])
      .filter(item => item.id.startsWith('go/folder'))
      .map(item => new ActionImpl(item, { store: {} }));

    if (folderItems.length > 0) {
      results.push(foldersSectionTitle);
      results.push(...folderItems);
    }
    if (dashboardItems.length > 0) {
      results.push(dashboardsSectionTitle);
      results.push(...dashboardItems);
    }
    return results;
  }, [kbarResults, searchResults, t]);

  const handleNavigationClick = (navigation: string) => {
    console.error(navigation);
    chrome.setMegaMenuOpen(false);
    chrome.setMegaMenuOpen(true);
    console.log(123)
    localStorage.setItem('grafana.navigation', navigation);
    window.dispatchEvent(new Event('localStorageChange'));
  };

  const handleGoToWeb = (url: string) => {
    window.open(url, "_blank", "noopener,noreferrer");
  }

  const handleGoToLocal = (url: string) => {
    if (url !== '') {
      location.push(url);
    }

    const uid = url.replace('/dashboards/f/', '').replace('/d/', '').split('/')[0];

    // url 移除/dashboards/f/和/d/，然后按照/分割取第0个为uid
    backendSrv.getDashboardNavByUid(uid).then(res => { 
      if (res.title) {
        localStorage.setItem('grafana.navigation', res.title);
      }
    }).catch(err => {
      console.log(err);
    });
  }

  const getListboxItemId = (id: number) => `kbar-listbox-item-${id}`;

    // 处理外部点击的回调
  const handleClickOutside = (event: any) => {
    // 若点击目标不在目标div内部，且目标div存在
    if (searchRef.current && !searchRef.current.contains(event.target)) {
      console.log('点击了div外部');
      query.setSearch('');
      query.getInput().focus();
      setInputValue('');
      // setIsVisible(false); // 示例：点击外部隐藏div
    }
  };

    // 挂载时添加监听，卸载时移除
  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  return (
    <>
      <Page
        navId="dashboards/home"
        layout={PageLayoutType.Canvas}
        pageNav={{ text: 'Home' }}
      >
        <div className={styles.dashboard}>
          <div className={styles.page}>
          <div className={styles.header}>
            <div className='logo'>
              <img src='/public/img/sec-logo.webp' alt='logo' width={100} />
            </div>
            <div className={styles.title1}>
              护航平台
            </div>
            <div className={styles.description}>
              安全一站式数智运维平台
            </div>
          </div>

          <div ref={searchRef} className={styles.searchWrapper}>
            <div className={styles.search} style={{marginBottom: '20px'}}>
              <div className={styles.searchInput}>
                <input 
                  style={{width: '100%', outline: 'transparent', background: 'transparent', border: 'transparent'}} 
                  type='text' 
                  placeholder='请输入搜索内容'
                  ref={query.inputRefSetter}
                  autoFocus
                  autoComplete="off"
                  role="combobox"
                  spellCheck="false"
                  aria-expanded={showing}
                  aria-controls="kbar-listbox"
                  aria-activedescendant={getListboxItemId(activeIndex)}
                  value={inputValue}
                  onChange={(event) => {
                    setInputValue(event.target.value);
                    query.setSearch(event.target.value);
                    options?.callbacks?.onQueryChange?.(event.target.value);
                  }}
                  className={styles.searchInput}
                />
              </div>
              <div className={styles.buttonGroup}>
                <Button style={{backgroundColor: '#0080ff', borderRadius: '20px'}} onClick={() => {}}>CMDB</Button>
                <Button style={{backgroundColor: 'rgba(0, 128, 255, 0.2)', color: '#0080ff', borderRadius: '20px'}}>处置记录</Button>
              </div>
            </div>

            {inputValue && (
              <FocusScope contain autoFocus>
                <div className={styles.searchResultsPanel}>
                  {isFetchingSearchResults && <LoadingBar width={100} delay={0} />}
                  {formattedResults.length > 0 ? (
                    <div>
                      {formattedResults.map((item: any, index: number) => { 
                        const renderedItem =
                            typeof item === 'string' ? (
                              <div key={index} className={styles.sectionHeader}>{item}</div>
                            ) : (
                              <div
                                onPointerDown={() => activeIndex !== index && query.setActiveIndex(index)}
                                onPointerMove={() => query.setActiveIndex(index)}
                                key={index}
                                onClick={() => handleGoToLocal(item.url)}
                                >
                                  <ResultItem action={item} active={activeIndex === index} currentRootActionId={rootActionId!} />
                              </div>
                            );
                  
                          return renderedItem;
                      })}
                    </div>
                  ) : (
                    <EmptyState
                        variant="not-found"
                        role="alert"
                        message={t('command-palette.empty-state.message', 'No results found')}
                      />
                  )}
                </div>
              </FocusScope>
            )}
          </div>

          <div className={styles.function}>
            <div className={styles.functionItem} onClick={() => { handleNavigationClick('基础运维'); }}>
              <Icon name='desktop' size='xxl' />
              <div className={styles.functionItemText}>
                基础运维
              </div>
            </div>
            <div className={styles.functionItem} onClick={() => { handleNavigationClick('成本运营'); }}>
              <Icon name='analytics' size='xxl' />
              <div className={styles.functionItemText}>
                成本运营
              </div>
            </div>
            <div className={styles.functionItem} onClick={() => { handleNavigationClick('风险管理'); }}>
              <Icon name='shield' size='xxl' />
              <div className={styles.functionItemText}>
                风险管理
              </div>
            </div>
            <div className={styles.functionItem} onClick={() => { handleNavigationClick('业务观测'); }}>
              <Icon name='bright' size='xxl' />
              <div className={styles.functionItemText}>
                业务观测
              </div>
            </div>
            <div className={styles.functionItem} onClick={() => { handleNavigationClick('厂内工具'); }}>
              <Icon name='bright' size='xxl' />
              <div className={styles.functionItemText}>
                厂内工具
              </div>
            </div>
          </div>

          <div className={styles.standardize}>
            <div className={styles.standardizeTitle}>规范制度</div>
            <div className={styles.standardizeContent}>
              <div style={{width: '100%', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '20px'}} >
                <div style={{flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', flexFlow: 'row', gap: '20px', cursor: 'pointer'}}
                onClick={() => { handleGoToWeb('https://www.baidu.com/'); }}
                >
                  <Icon name='desktop' size='xxl' />
                  <div style={{textAlign: 'center', flex: 1}}>
                    百度
                  </div>
                </div>
                <div style={{flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', flexFlow: 'row', gap: '20px'}}>
                  <Icon name='desktop' size='xxl' />
                  <div style={{textAlign: 'center', flex: 1}}>
                    稳定性军规
                  </div>
                </div>
                <div style={{flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', flexFlow: 'row', gap: '20px'}}>
                  <Icon name='desktop' size='xxl' />
                  <div style={{textAlign: 'center', flex: 1}}>
                    稳定性军规333333
                  </div>
                </div>
                <div style={{flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', flexFlow: 'row', gap: '20px'}}>
                  <Icon name='desktop' size='xxl' />
                  <div style={{textAlign: 'center', flex: 1}}>
                    稳定性军规
                  </div>
                </div>
                <div style={{flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', flexFlow: 'row', gap: '20px'}}>
                  <Icon name='desktop' size='xxl' />
                  <div style={{textAlign: 'center', flex: 1}}>
                    稳定性军规
                  </div>
                </div>
                <div style={{flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', flexFlow: 'row', gap: '20px'}}>
                  <Icon name='desktop' size='xxl' />
                  <div style={{textAlign: 'center', flex: 1}}>
                    稳定性军规
                  </div>
                </div>
              </div>
              
            </div>
          </div>

          <div className={styles.requestPermission}>
            <Button className={styles.requestPermissionBtn}>
              申请权限
            </Button>
          </div>
        </div>
      </div>
      </Page>
    </>
  );
};

function getStyles(theme: GrafanaTheme2) {
  return {
    dashboard: css({
      margin: theme.spacing(2),
      background: theme.colors.background.primary,
      borderRadius: '10px',
      height: '100%',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      paddingTop: theme.spacing(10),
      paddingBottom: theme.spacing(10),
      overflowX: 'auto',
    }),
    page: css({
      width: '90%',
      minWidth: '800px',
      maxWidth: '1000px',
      overflowX: 'auto',
      overflowY: 'auto',
      position: 'relative',
    }),
    header: css({
      display: 'flex',
      flexFlow: 'column',
      justifyItems: 'center',
      alignItems: 'center',
      marginBottom: '20px',
    }),
    title1: css({
      fontSize: '30px',
      fontWeight: 'bold',
      color: theme.colors.text.primary,
      paddingTop: '20px',
    }),
    description: css({
      fontSize: '14px',
      color: theme.colors.text.secondary,
      paddingTop: '10px',
    }),
    search: css({
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
      padding: theme.spacing(1),
      paddingLeft: theme.spacing(2),
      marginBottom: '20px',
      width: '100%',
      borderRadius: '40px',
      border: `1px solid ${theme.colors.border.weak}`,
    }),
    buttonGroup: css({
      display: 'flex',
      alignItems: 'center',
      gap: theme.spacing(2),
      [theme.breakpoints.down('sm')]: {
        flexDirection: 'column',
        alignItems: 'stretch',
      },
    }),
    function: css({
      display: 'grid',
      gridTemplateColumns: 'repeat(5, 1fr)',
      gap: theme.spacing(3),
      alignItems: 'center',
      position: 'sticky',
      top: 0,
      zIndex: theme.zIndex.navbarFixed,
      padding: theme.spacing(2, 0),
      marginBottom: '20px',
      [theme.breakpoints.down('sm')]: {
        flexDirection: 'column',
        gap: theme.spacing(1),
        alignItems: 'stretch',
      },
    }),
    functionItem: css({
      display: 'flex',
      flexFlow: 'column',
      alignItems: 'center',
      background: theme.colors.background.secondary,
      color: theme.colors.text.primary,
      padding: theme.spacing(3),
      width: '100%',
      borderRadius: '14px',
      gap: theme.spacing(1),
      cursor: 'pointer',
      [theme.breakpoints.down('sm')]: {
        flexDirection: 'column',
        alignItems: 'stretch',
      },
    }),
    functionItemText: css({
      fontSize: '14px',
      color: theme.colors.text.primary,
    }),
    standardize: css({
      display: 'flex',
      flexFlow: 'column',
      alignItems: 'center',
      justifyContent: 'center',
      paddingTop: theme.spacing(4),
      paddingBottom: theme.spacing(4),
      gap: theme.spacing(2),
      background: theme.colors.background.secondary,
      borderRadius: '16px',
      [theme.breakpoints.down('sm')]: {
        alignItems: 'stretch',
      },
    }),
    standardizeTitle: css({
      fontSize: '20px',
      fontWeight: 'bold',
      color: theme.colors.text.primary,
    }),
    standardizeContent: css({
      display: 'flex',
      gridTemplateColumns: 'repeat(4, 1fr)',
      gap: theme.spacing(4),
      paddingLeft: theme.spacing(8),
      paddingRight: theme.spacing(8),
      width: '100%',
      [theme.breakpoints.down('sm')]: {
        gridTemplateColumns: 'repeat(2, 1fr)',
      },
    }),
    iconTitle: css({
      display: 'none',
      [theme.breakpoints.up('sm')]: {
        display: 'flex',
        alignItems: 'center',
      },
    }),
    title: css({
      overflow: 'hidden',
      textOverflow: 'ellipsis',
      whiteSpace: 'nowrap',
      display: 'flex',
      fontSize: theme.typography.h4.fontSize,
      margin: 0,
    }),
    body: css({
      label: 'body',
      display: 'flex',
      flex: 1,
      flexDirection: 'column',
      overflowY: 'auto',
    }),
    requestPermission: css({
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      gap: theme.spacing(2),
      marginTop: theme.spacing(4),
    }),
    requestPermissionBtn: css({
      backgroundColor: theme.colors.background.primary,
      color: 'rgba(0, 128, 255, 1)',
      borderRadius: '20px',
      border: '1px solid',
      borderColor: theme.colors.border.medium,
      ":hover": {
        backgroundColor: 'rgba(0, 128, 255, 0.1)',
        color: 'rgba(0, 128, 255, 1)',
      }
    }),

    searchWrapper: css({
      width: '100%',
      marginBottom: theme.spacing(4),
      position: 'relative',
      height: 'auto',
      zIndex: theme.zIndex.modal + 1,
    }),

    searchInputContainer: css({
      display: 'flex',
      alignItems: 'center',
      gap: theme.spacing(1),
      padding: theme.spacing(1.5, 2),
      width: '100%',
      borderRadius: '40px',
      border: `1px solid ${theme.colors.border.weak}`,
      background: theme.colors.background.primary,
      boxShadow: theme.shadows.z1,
      '&:focus-within': {
        borderColor: theme.colors.primary.main,
        boxShadow: `0 0 0 2px ${theme.colors.primary.border}`,
      },
    }),

    searchIcon: css({
      color: theme.colors.text.secondary,
      flexShrink: 0,
    }),

    searchInput: css({
      width: '100%',
      outline: 'none',
      border: 'none',
      background: 'transparent',
      color: theme.colors.text.primary,
      fontSize: theme.typography.fontSize,
      padding: theme.spacing(0.5, 0),
      '&::placeholder': {
        color: theme.colors.text.secondary,
        opacity: 1,
      },
    }),

    searchResultsPanel: css({
      position: 'absolute',
      top: '100%',
      left: 0,
      right: 0,
      marginTop: theme.spacing(1),
      width: '100%',
      background: theme.colors.background.primary,
      borderRadius: theme.shape.radius.default,
      border: `1px solid ${theme.colors.border.weak}`,
      boxShadow: theme.shadows.z3,
      overflow: 'hidden',
      zIndex: theme.zIndex.portal - 1,
      maxHeight: 400,
      overflowY: 'auto',
    }),

    sectionHeader: css({
      padding: theme.spacing(1.5, 2),
      fontSize: theme.typography.bodySmall.fontSize,
      fontWeight: theme.typography.fontWeightMedium,
      color: theme.colors.text.secondary,
      borderBottom: `1px solid ${theme.colors.border.weak}`,
      backgroundColor: theme.colors.background.secondary,
    }),

    emptyState: css({
      padding: theme.spacing(4),
    }),
  };
}
